package android.concisapp.fragments;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.concisapp.DetailActivity;
import android.concisapp.R;
import android.concisapp.list.ListHolder;
import android.concisapp.parser.ParserListNews;
import android.concisapp.parser.RssItem;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

public class NewsFragment extends android.support.v4.app.Fragment {

	public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
	private View rootView;
	private Activity thisActivity;
	private ListView listView;
	private ArrayList<RssItem> data;
	private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {

		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			Log.i("PULSADO", "ITEM " + position);
			Intent i = new Intent(getActivity(), DetailActivity.class);
			i.putExtra("data", (String) data.get(position).getDescription());
			getActivity().startActivity(i);
		}

	};

	public static final android.support.v4.app.Fragment newInstance(
			String message) {
		android.support.v4.app.Fragment f = (android.support.v4.app.Fragment) new NewsFragment();
		Bundle bdl = new Bundle(1);
		bdl.putString(EXTRA_MESSAGE, message);
		f.setArguments(bdl);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		thisActivity = getActivity();
		rootView = inflater.inflate(R.layout.noticias, container, false);
		listView = (ListView) rootView.findViewById(R.id.rssListView);
		new GetFeedTask().execute();
		return rootView;
	}

	private class GetFeedTask extends
			AsyncTask<String, Void, ArrayList<RssItem>> {

		@Override
		protected void onPreExecute() {
			Log.d("GETFEED", "PREEXECUTE");
			LinearLayout l = new LinearLayout(thisActivity);
			TextView t = new TextView(thisActivity);
			t.setText(R.string.app_name);
			l.addView(t);
//			ImageView i = new ImageView(thisActivity);
//			i.setImageResource(R.drawable.loading_big);
//			l.addView(i);
//			thisActivity.setContentView(l);
		}

		@Override
		protected ArrayList<RssItem> doInBackground(String... params) {
			ParserListNews p = new ParserListNews();
			return p.getArrayItem();
		}

		@Override
		protected void onPostExecute(ArrayList<RssItem> result) {
			Log.d("GETFEED", "Finished!");

			final StableArrayAdapter adapter = new StableArrayAdapter(
					getActivity(), result);
			listView.setOnItemClickListener(listener);
			listView.setAdapter(adapter);
		}
	}

	private class StableArrayAdapter extends BaseAdapter {

		private LayoutInflater inflater = null;
		private ListHolder holder;

		// private int convertViewCounter = 0;

		public StableArrayAdapter(Context c, ArrayList<RssItem> d) {

			data = d;
			inflater = LayoutInflater.from(c);
		}

		// OnClickListener clickListener = new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Log.i("PULSA", " " + v.);
		// Intent i = new Intent(getActivity(), DetailActivity.class);
		// // i.putExtra("data", data.get(getI))
		// getActivity().startActivity(i);
		// }
		// };

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int arg0) {
			return data.get(arg0);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.list_adapter, null);

				// convertViewCounter++;

				holder = new ListHolder();

				holder.titleView = (TextView) convertView
						.findViewById(R.id.titleViewList);
				holder.dateView = (TextView) convertView
						.findViewById(R.id.dateViewList);
				holder.imageView = (ImageView) convertView
						.findViewById(R.id.imageViewList);
				convertView.setTag(holder);

			} else
				holder = (ListHolder) convertView.getTag();

			holder.titleView
					.setText(getTitleOnly(data.get(position).getTitle()));
			holder.dateView.setText(formatDate(data.get(position).getTitle()));
			ImageLoader.getInstance().displayImage(
					data.get(position).getThumbnail(), holder.imageView);

			return convertView;

		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public String getTitleOnly(String title) {
			String result = "";
			int index = title.indexOf(':');
			result = title.substring(index + 2);
//			Log.i("TITLE ONLY", "title " + result);
			return result;
		}

		public String formatDate(String title) {
			String formattedDate = "";
			int index = title.indexOf(':');
			formattedDate = title.substring(0, index);
//			Log.i("FORMATTED DATE", "title " + formattedDate);
			return formattedDate;
		}

	}

	private class ImageFeedTask extends AsyncTask<Object, Void, Bitmap> {

		private Bitmap bmp;
		private ListHolder holder;

		@Override
		protected Bitmap doInBackground(Object... params) {
			try {
				URL url = (URL) params[0];
				holder = (ListHolder) params[1];
				bmp = BitmapFactory.decodeStream(url.openConnection()
						.getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}
			return bmp;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			holder.imageView.setImageBitmap(result);
		}
	}

}
